import tkinter as tk
from tkinter import filedialog, messagebox
import re
import os

def is_special_line(line):
    """判断是否为需要过滤的非正文内容"""
    line = line.strip()
    # 规则：全中文、无标点、长度<=20
    if 1 <= len(line) <= 20:
        if re.fullmatch(r'[\u4e00-\u9fff·]+$', line):  # 允许包含中文分隔符"·"
            if not re.search(r'[。！？!?]', line):     # 不含任何标点
                return True
    return False

def select_input_file():
    filepath = filedialog.askopenfilename()
    if filepath:
        input_entry.delete(0, tk.END)
        input_entry.insert(0, filepath)
        # 自动设置输出路径
        dirname = os.path.dirname(filepath)
        output_path = os.path.join(dirname, "output.txt")
        output_entry.delete(0, tk.END)
        output_entry.insert(0, output_path)

def select_output_file():
    filepath = filedialog.asksaveasfilename(
        defaultextension=".txt",
        initialfile=output_entry.get() or "output.txt"
    )
    if filepath:
        output_entry.delete(0, tk.END)
        output_entry.insert(0, filepath)

def convert_file():
    input_path = input_entry.get()
    output_path = output_entry.get()
    
    try:
        n = int(n_entry.get() or 3)
        start_text = start_entry.get() or "如是我闻"
    except ValueError:
        messagebox.showerror("错误", "n必须为整数")
        return
    
    try:
        with open(input_path, 'r', encoding='utf-8') as f:
            raw_content = f.read()

        # 预处理流程
        lines = raw_content.split('\n')
        filtered_lines = []
        
        # 第一遍过滤：删除特殊行
        for line in lines:
            if not is_special_line(line):
                filtered_lines.append(line)
        
        # 合并内容并查找起始位置
        merged_content = ''.join(filtered_lines)
        start_pos = merged_content.find(start_text)
        if start_pos == -1:
            messagebox.showwarning("提示", "未找到起始文本，将从开头处理")
        else:
            merged_content = merged_content[start_pos:]
        
        # 分句处理（保留原标点）
        sentences = re.findall(r'[^。！？]*[。！？]|[^。！？]+$', merged_content)
        sentences = [s.strip() for s in sentences if s.strip()]
        
        # 第二遍过滤：排除空句子和单字句
        sentences = [s for s in sentences if len(s) > 1]
        
        output_lines = []
        if n == 1:
            for i, sentence in enumerate(sentences, start=1):
                label = f"({i})"
                output_lines.append(f"{label}: {sentence}\n")
        else:
            for i in range(len(sentences) - n + 1):
                group = sentences[i:i+n]
                label = f"({', '.join(map(str, range(i+1, i+n+1)))})"
                processed_text = ''.join(group)
                output_lines.append(f"{label}: {processed_text}\n")
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.writelines(output_lines)
        messagebox.showinfo("完成", f"转换完成，共处理{len(sentences)}句")
    except Exception as e:
        messagebox.showerror("错误", str(e))

# GUI界面
app = tk.Tk()
app.title("智能文本转换器")

# 输入文件组件
tk.Label(app, text="输入文件:").grid(row=0, column=0, padx=5, pady=5)
input_entry = tk.Entry(app, width=50)
input_entry.grid(row=0, column=1, padx=5, pady=5)
tk.Button(app, text="选择文件", command=select_input_file).grid(row=0, column=2, padx=5, pady=5)

# 起始文本
tk.Label(app, text="起始文本:").grid(row=1, column=0, padx=5, pady=5)
start_entry = tk.Entry(app, width=15)
start_entry.insert(0, "如是我闻")
start_entry.grid(row=1, column=1, padx=5, pady=5, sticky='w')

# 分组设置
tk.Label(app, text="每n句话:").grid(row=2, column=0, padx=5, pady=5)
n_entry = tk.Entry(app, width=5)
n_entry.insert(0, "3")
n_entry.grid(row=2, column=1, padx=5, pady=5, sticky='w')

# 输出文件组件
tk.Label(app, text="输出文件:").grid(row=3, column=0, padx=5, pady=5)
output_entry = tk.Entry(app, width=50)
output_entry.grid(row=3, column=1, padx=5, pady=5)
tk.Button(app, text="选择路径", command=select_output_file).grid(row=3, column=2, padx=5, pady=5)

# 转换按钮
tk.Button(app, text="开始转换", command=convert_file).grid(row=4, column=1, pady=10)

app.mainloop()